//
//  MCCommunityViewController.swift
//  StoreManage
//
//  Created by MC on 2018/6/20.
//  Copyright © 2018年 MC. All rights reserved.
//

import UIKit

class MCCommunityViewController: MCViewController {
    
    public var clerkId = 0   // 可是是自己的或者其他的社区
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        sendNetworking()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        managerClosure()
        
    }
    
    // MARK: - System Delegate
    
    // MARK: - Custom Delegate
    
    // MARK: - Closure
    func managerClosure() {

    }
    // MARK: - Action
    @objc func addButtonClicked() {
        
        if MCUserinfo_getLevel() < MCRole_manager {
            MCHUD_text(message: "只有店长才可编辑", view: self.view, delay: 1.2)
            return;
        }

        
        
        let vc = MCAddCommunityViewController()
        vc.clerkId = clerkId
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
    // MARK: - Network
    func sendNetworking() {
        
        dataArrayM.removeAllObjects()
        
        let para = [
            "clerkId" : clerkId,
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_findCommunityListByUserId, para: para as [String : AnyObject], vc: self,hudSuperView: nil,isHiddenTabbar: true, success: { (response) in
            let dataArray = response["data"] as? NSArray ?? []
            

            if dataArray.count == 0 {
                self.tableView.showBgImage()
            } else {
                self.tableView.hideBgImage()
                for dict in dataArray {
                    let model = MCCommunityModel()
                    model.setValuesForKeys(dict as? [String:Any] ?? [:])
                    self.dataArrayM.add(model)
                }
                self.tableView.reloadData()
            }
            
        }, dislike: { (response) in }) { (error) in }
    }
    
    // MARK: - Method
    func baseSetting() {
        self.title = "配送社区"
        self.view.backgroundColor = UIColor.white
    }
    
    func initUI() {
        view.addSubview(tableView)
        tableView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view).inset(UIEdgeInsetsMake(0, 0, CGFloat(44), 0))
        }
        
        view.addSubview(addButton)
        addButton.snp.remakeConstraints { (make) ->Void in
            make.centerX.equalTo(view)
            make.bottom.equalTo(0)
            make.size.equalTo(CGSize.init(width: MCScreenWidth, height: 44))
        }
    }
    
    
    func defaultAddress(model:MCCommunityModel,sender:UIButton) {
        
        var isDefault = 0
        var str = ""
        
        if sender.isSelected {
            isDefault = 0
            str = "取消默认地址"
        } else {
            isDefault = 1
            str = "设置为默认地址"

        }
        
        let para = [
            "province" : model.province,
            "city" : model.city,
            "area" : model.area,
            "address" : model.address,
            "clerkId" : model.clerkId,
            "communityName" : model.communityName,
            "isDefault" : isDefault,
            "communityId" : model.communityId
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_updateCommunityOfUser, para: para as [String : AnyObject], vc: self,hudSuperView: nil,isHiddenTabbar: true, success: { (response) in
            
            MCHUD_text(message: str, view: self.view, delay: 1.2)

            sender.isSelected = !sender.isSelected
            self.sendNetworking()
        }, dislike: { (response) in }) { (error) in }
    }
    
    func editAddress(model:MCCommunityModel) {
        let vc = MCAddCommunityViewController()
        vc.model = model
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
    
    func deleteAddress(model:MCCommunityModel) {
        let para = [
            "communityId" : model.communityId,
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_deleteCommunityOfUser, para: para as [String : AnyObject], vc: self,hudSuperView: nil,isHiddenTabbar: true, success: { (response) in

            MCHUD_text(message: "删除成功", view: self.view, delay: 1.2)
            self.sendNetworking()
        }, dislike: { (response) in }) { (error) in }
    }
    
    // MARK: - Setter & Getter
    lazy private var tableView: MCTableView = {
        let tableView = MCTableView.init(frame: CGRect.zero, style: UITableViewStyle.plain)
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()
    
    lazy var dataArrayM: NSMutableArray = {
        let arrayM = NSMutableArray()
        return arrayM
    }()
    
    lazy var addButton: UIButton = {
        let button = UIButton.init(type: UIButtonType.custom)
        button.titleLabel?.font = MCFont(14)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitle("新增配送社区", for:.normal)
        button.backgroundColor = UIColor.MCMain
        button.addTarget(self, action: #selector(addButtonClicked), for: .touchUpInside)
        return button
    }()

}

extension MCCommunityViewController : UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArrayM.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 140
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = MCCommunityCell.init(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")
        
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        cell.backgroundColor = UIColor.MCGray_light
        cell.model = self.dataArrayM[indexPath.row] as! MCCommunityModel
        
        cell.closure = { tag,model,sender in
            switch tag {
            case 0:
                self.defaultAddress(model: model, sender: sender)
                print("地址")
            case 1:
                print("编辑")
                self.editAddress(model: model)
            default:
                self.deleteAddress(model: model)
                print("删除")
            }
        }
        return cell
    }
}

